package com.panshi.modules.system.util;


import com.alibaba.fastjson.JSONObject;
import com.panshi.api.util.CommonResult;
import com.panshi.modules.system.bean.BeiSysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/*@Order(1)
@WebFilter(filterName = "PiceaFilter")
@Component*/
public class PiceaFilter /*implements Filter*/ {


    private String[] urls = new String[] {"/role"
            ,"/function","/sys"};
    /**
     * 可以初始化Filter在web.xml里面配置的初始化参数
     * filter对象只会创建一次，init方法也只会执行一次。
     * @param filterConfig
     * @throws ServletException
     */
    //@Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 主要的业务代码编写方法
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    //@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse=(HttpServletResponse)servletResponse;
        String uri = request.getRequestURI();//请求的地址
        //判断是否属于需要过滤的资源
        boolean pass = false;
        if(urls != null){
            for (int i = 0; i < urls.length; i++) {
                System.out.println(uri.indexOf(urls[i]));
                if (uri.indexOf(urls[i])>-1){
                    pass = true;
                    break;
                }
            }
        }
        if (pass == true) {//需要登录之后才能访问
             BeiSysUser myuser = (BeiSysUser)request.getSession().getAttribute("myuser");
            if (myuser!=null) {
                filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    httpResponse.sendRedirect("/login");
                }
        } else {
            //正常请求
            System.out.println("正常请求");
        System.out.println("我进来 =============");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    /**
     * 在销毁Filter时自动调用。
     */
    //@Override
    public void destroy() {

    }
}